<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Object oriented programming</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, OOP, object oriented programming, programming, language, learn Python">
<meta name="description" content="In this part of the Python tutorial, we
cover object-oriented programming.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>

<h1>Object-oriented programming</h1>

<p>
In this part of the Python programming tutorial, we will talk about object 
oriented programming in Python.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
There are three widely used programming paradigms there. Procedural programming, 
functional programming and object-oriented programming. Python supports both 
procedural and object-oriented programming. There is some limited support for f
unctional programming too. 
</p>

<p>
<b>Object-oriented programming (OOP)</b> is a programming paradigm that uses 
objects and their interactions to design applications and computer programs.
(Wikipedia)
</p>

<p>
There are some basic programming concepts in OOP:
</p>

<ul>
<li>Abstraction</li>
<li>Polymorphism</li>
<li>Encapsulation</li>
<li>Inheritance</li>
</ul>

<p>
The <b>abstraction</b> is simplifying complex reality by modelling classes 
appropriate to the problem. The <b>polymorphism</b> is the process of using 
an operator or function in different ways for different data input. The 
<b>encapsulation</b> hides the implementation details of a class from other objects. 
The <b>inheritance</b> is a way to form new classes  using classes that have already been defined.
</p>

<h2>Objects</h2>

<p>
Everything in Python is an object. Objects are basic building blocks of a Python OOP program. 
</p>

<pre class="code">
#!/usr/bin/python

# objects.py

import sys


def function(): pass


print type(1)
print type("")
print type([])
print type({})
print type(())
print type(object)
print type(function)
print type(sys)
</pre>

<p>
In this example we show, that all these entities are in fact objects. 
The <b class="keyword">type()</b> function returns the
type of the object specified. 
</p>

<pre>
$ ./objects.py 
&lt;type 'int'&gt;
&lt;type 'str'&gt;
&lt;type 'list'&gt;
&lt;type 'dict'&gt;
&lt;type 'tuple'&gt;
&lt;type 'type'&gt;
&lt;type 'function'&gt;
&lt;type 'module'&gt;
</pre>


<h2>The class keyword</h2>

<p>
The previous objects were all built-in objects of the Python programming language. 
The user defined objects are created
using the <b class="keyword">class</b> keyword. The class is a blueprint 
that defines a nature of a future object. 
From classes we construct instances. An <b>instance</b> is a specific 
object created from a particular class. 
For example,  Huck might be an instance of a Dog class. 
</p>

<pre class="code">
#!/usr/bin/python

# first.py

class First:
   pass

fr = First()

print type(fr)
print type(First)
</pre>

<p>
This is our first class. The body of the class is left empty for now. It is a
convention to give classes a name that starts with a capital letter.
</p>

<pre class="explanation">
fr = First()
</pre>

<p>
Here we create a new instance of the First class. Or in other words, we 
instantiate the First class. The fr is a reference to our new object. 
</p>

<pre>
$ ./first.py 
&lt;type 'instance'&gt;
&lt;type 'classobj'&gt;
</pre>

<p>
Here we see that fr is an instance object and First is a class object. 
</p>

<p>
Inside a class, we can define attributes and methods. An <b>attribute</b> is 
a characteristic of an object. This can be for example a salary of an employee. 
A <b>method</b> defines operations that we can perform with our objects. A method 
might define a cancellation of an account. Technically, attributes are variables 
and methods are functions defined inside a class. 
</p>

<h2>Attributes</h2>

<p>
Attributes are characteristics of an object. A special method called 
<b class="keyword">__init__()</b> is used to initialize the attributes of an object. 
</p>

<pre class="code">
#!/usr/bin/python

# initialize.py


class Cat:
   def __init__(self, name):
      self.name = name


missy = Cat('Missy')
lucky = Cat('Lucky')

print missy.name
print lucky.name
</pre>

<p>
In this code example, we have a Cat class. The special method 
<b class="keyword">__init__()</b> is called automatically right after 
the object has been created. 
</p>

<pre class="explanation">
 def __init__(self, name):
</pre>

<p>
Each method in a class definition begins with a reference to the instance 
object. It is by convention named <b>self</b>. There is nothing special 
about the self name. We could name it this, for example. The name is the 
argument. The value is passed during the class instantiation. 
</p>

<pre class="explanation">
 self.name = name
</pre>

<p>
Here we pass an attribute to an instance object. 
</p>

<pre class="explanation">
 missy = Cat('Missy')
 lucky = Cat('Lucky')
</pre>

<p>
Here we instantiate two objects. Missy and Lucky cats. The number of arguments 
must correspond to the <b class="keyword">__init__()</b> method of the class 
definition. The 'Missy' and 'Lucky' strings become the name
parameter of the <b class="keyword">__init__()</b> method.
</p>


<pre class="explanation">
 print missy.name
 print lucky.name
</pre>

<p>
Here we print the instance variables of two cat objects. Each instance of a 
class can have their own attributes. 
</p>

<pre>
$ ./initialize.py 
Missy
Lucky
</pre>

<p>
The attributes can be assigned dynamically, not just during initialization. 
This shows the next example. 
</p>

<pre class="code">
#!/usr/bin/python

# dynamic.py

class Dynamic:
   pass


d = Dynamic()
d.name = "Dynamic"
print d.name
</pre>

<p>
We define and create an empty Dynamic class. 
</p>

<pre class="explanation">
 d.name = "Dynamic"
</pre>

<p>
This line of code creates a new name attribute. 
</p>

<pre>
$ ./dynamic.py 
Dynamic
</pre>

<p>
So far, we have been talking about the instance attributes. In Python there 
are also so called <b>class object attributes</b>. 
Class object attributes are same for all instances of a class. 
</p>


<pre class="code">
#!/usr/bin/python

# cat.py


class Cat:
   species = 'mammal'

   def __init__(self, name, age):
      self.name = name
      self.age = age


missy = Cat('Missy', 3)
lucky = Cat('Lucky', 5)

print missy.name, missy.age
print lucky.name, lucky.age

print Cat.species
print missy.__class__.species
print lucky.__class__.species
</pre>

<p>
In our example, we have two cats with specific name and age attributes. Both
cats share some characteristics. Missy and Lucky are both mammals. This is 
reflected in a class level attribute species. The attribute is defined outside 
any method name in the body of a class. 
</p>

<pre class="explanation">
 print Cat.species
 print missy.__class__.species
</pre>

<p>
There are two ways, how we can access the class object attributes. Either via 
the name of the Cat class, or with the help of a special <b class="keyword">__class__</b> attribute. 
</p>

<pre>
$ ./cat.py 
Missy 3
Lucky 5
mammal
mammal
mammal
</pre>

<h2>Methods</h2>

<p>
Methods are functions defined inside the body of a class. They are used to 
perform operations with the attributes of our objects. Methods are essential 
in <b>encapsulation</b> concept of the OOP paradigm. For example, we might 
have a connect() method in our AccessDatabase class. We need not to be informed, 
how exactly the method connect connects to the database. We only know, that it 
is used to connect to a database. This is essential in dividing responsibilities 
in programming. Especially in large applications. 
</p>

<pre class="code">
#!/usr/bin/python

# circle.py


class Circle:
   pi = 3.141592

   def __init__(self, radius=1):
      self.radius = radius 

   def area(self):
      return self.radius * self.radius * Circle.pi

   def setRadius(self, radius):
      self.radius = radius

   def getRadius(self):
      return self.radius


c = Circle()

c.setRadius(5)
print c.getRadius()
print c.area()
</pre>

<p>
In the code example, we have a Circle class. We define three new methods.
</p>

<pre class="explanation">
 def area(self):
    return self.radius * self.radius * Circle.pi
</pre>

<p>
The area() method returns the area of a circle. 
</p>

<pre class="explanation">
 def setRadius(self, radius):
    self.radius = radius
</pre>

<p>
The setRadius() method sets a new value for a radius attribute. 
</p>

<pre class="explanation">
 def getRadius(self):
    return self.radius
</pre>

<p>
The getRadius() method returns the current radius. 
</p>

<pre class="explanation">
 c.setRadius(5)
</pre>

<p>
The method is called on an instance object. The c object is paired with 
the self parameter of the class definition.
The number 5 is paired with the radius parameter. 
</p>

<pre>
$ ./circle.py 
5
78.5398
</pre>

<p>
In Python, we can call methods in two ways. There are <b>bounded</b> 
and <b>unbounded</b> method calls. 
</p>

<pre class="code">
#!/usr/bin/python

# methods.py

class Methods:
   def __init__(self):
      self.name = 'Methods'

   def getName(self):
      return self.name


m = Methods()

print m.getName()
print Methods.getName(m)
</pre>

<p>
In this example, we demostrate both method calls. 
</p>

<pre class="explanation">
 print m.getName()
</pre>

<p>
This is the <b>bounded</b> method call. The Python interpreter automatically 
pairs the m instance with the self parameter.
</p>

<pre class="explanation">
 print Methods.getName(m)
</pre>

<p>
And this is the <b>unbounded</b> method call. The instance object is 
explicitly given to the getName() method. 
</p>

<pre>
$ ./methods.py 
Methods
Methods
</pre>


<h2>Inheritance</h2>

<p>
The inheritance is a way to form new classes using classes that have 
already been defined. The newly formed classes are called <b>derived</b>
classes, the classes that we derive from are called <b>base</b> classes. 
Important benefits of inheritance are code reuse and reduction of complexity 
of a program. The derived classes (descendants) override or extend the 
functionality of base classes (ancestors). 
</p>

<pre class="code">
#!/usr/bin/python

# inherit.py


class Animal:
   def __init__(self):
      print "Animal created"

   def whoAmI(self):
      print "Animal"

   def eat(self):
      print "Eating"


class Dog(Animal):
   def __init__(self):
      Animal.__init__(self)
      print "Dog created"

   def whoAmI(self):
      print "Dog"

   def bark(self):
      print "Woof!"


d = Dog()
d.whoAmI()
d.eat()
d.bark()
</pre>

<p>
In this example, we have two classes. Animal and Dog. The animal is the 
base class, the Dog is the derived class. 
The derived class inherits the functionality of the base class. It is shown 
by the eat() method. The derived class modifies existing behaviour of the 
base class, shown by the whoAmI() method. Finally, the derived class extends 
the functionality of the base class, by defining a new bark() method. 
</p>

<pre class="explanation">
 class Dog(Animal):
    def __init__(self):
       Animal.__init__(self)
       print "Dog created"
</pre>

<p>
We put the ancestor classes in round brackets after the name of the 
descendant class. If the derived class provides it's own <b class="keyword">__init__()</b> 
method, it must explicitly call the base class <b class="keyword">__init__()</b> method.
</p>

<pre>
$ ./inherit.py 
Animal created
Dog created
Dog
Eating
Woof!
</pre>

<h2>Polymorphism</h2>

<p>
The polymorphism is the process of using an operator or function in
 different ways for different data input.
In practical terms, polymorphism means that if class B inherits from 
class A, it doesn’t have to inherit everything about class A; it can 
do some of the things that class A does differently. (wikipedia)
</p>

<pre class="code">
#!/usr/bin/python

# basic.py


a = "alfa"
b = (1, 2, 3, 4)
c = ['o', 'm', 'e', 'g', 'a']

print a[2]
print b[1]
print c[3]
</pre>

<p>
Python programming language uses polymorphism extensively in built-in types. 
Here we use the same indexing operator for three different data types. 
</p>

<pre>
$ ./basic.py 
f
2
g
</pre>

<p>
Polymorphism is most commonly used when dealing with inheritance. 
</p>

<pre class="code">
#!/usr/bin/python

# polymorphism.py


class Animal:
   def __init__(self, name=''):
      self.name = name

   def talk(self):
      pass


class Cat(Animal):
   def talk(self):
      print "Meow!"


class Dog(Animal):
   def talk(self):
      print "Woof!"


a = Animal()
a.talk()

c = Cat("Missy")
c.talk()

d = Dog("Rocky")
d.talk()
</pre>

<p>
Here we have two species. A dog and a cat. Both are animals. The Dog class 
and the Cat class inherit the Animal class. 
They have a talk() method, which gives different output for them.  
</p>

<pre>
$ ./polymorphism.py 
Meow!
Woof!
</pre>






<h2>Special Methods</h2>


<p>
Classes in Python programming language can implement certain operations 
with special method names. These methods are not called directly, but by a 
specific language syntax. This is similar to what is known as
<b>operator overloading</b> in C++ or Ruby.
</p>

<pre class="code">
#!/usr/bin/python

# book.py

class Book:
   def __init__(self, title, author, pages):
      print "A book is created"
      self.title = title
      self.author = author
      self.pages = pages

   def __str__(self):
      return "Title:%s , author:%s, pages:%s " % \
              (self.title, self.author, self.pages)

   def __len__(self):
      return self.pages

   def __del__(self):
      print "A book is destroyed"


book = Book("Inside Steve's Brain", "Leander Kahney", 304)

print book
print len(book)
del book
</pre>

<p>
In our code example, we have a book class. Here we introduce four special methods. 
The <b class="keyword">__init__()</b>, <b class="keyword">__str__()</b>, 
<b class="keyword">__len__()</b> and the <b class="keyword">__del__()</b> methods. 
</p>

<pre class="explanation">
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
</pre>

<p>
Here we call the <b class="keyword">__init__()</b> method. The method creates a 
new instance of a Book class.
</p>

<pre class="explanation">
print book
</pre>

<p>
The print keyword calls the <b class="keyword">__str__()</b> method. This method 
should return an informal string representation of an object. 
</p>

<pre class="explanation">
print len(book)
</pre>

<p>
The <b class="keyword">len()</b> function invokes the <b class="keyword">__len__()</b> 
method. In our case, we print the number of pages of our book.
</p>

<pre class="explanation">
del book
</pre>

<p>
The del keyword deletes an object. It calls the <b class="keyword">__del__()</b> method.
</p>

<p>
In the next example we implement a vector class and demonstrate addition and 
substraction operations on it. 
</p>

<pre class="code">
#!/usr/bin/python

# vector.py


class Vector:

  def __init__(self, data):
    self.data = data

  def __str__(self):
    return repr(self.data)

  def __add__(self, other):
    data = []
    for j in range(len(self.data)):
      data.append(self.data[j] + other.data[j])
    return Vector(data)

  def __sub__(self, other):
    data = []
    for j in range(len(self.data)):
      data.append(self.data[j] - other.data[j])
    return Vector(data)


x = Vector([1, 2, 3])
y = Vector([3, 0, 2])
print x + y
print y - x
</pre>

<p>

</p>

<pre class="explanation">
  def __add__(self, other):
    data = []
    for j in range(len(self.data)):
      data.append(self.data[j] + other.data[j])
    return Vector(data)
</pre>

<p>
Here we implement the addition operation of vectors. The <b class="keyword">__add__()</b> method is called, when we
add two Vector objects with the + operator. Here we add each member of the respective vectors. 
</p>

<pre>
$ ./vector.py 
[4, 2, 5]
[2, -2, -1]
</pre>

<p>
In this part of the Python tutorial, we have covered object-oriented programming in Python.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡  
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified July 6, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

